package Demo1;
import com.sun.org.apache.xpath.internal.objects.XString;

import java.sql.*;
import java.util.Scanner;

public class demo1 {
    public static void main(String[] args) throws SQLException {
        // 修改用户名和密码
        /***
         * 1.注册驱动
         * 2.获取连接
         * 3.创建表结构（statement）对象
         * 4.执行SQL语句
         * 5.操作返回结果
         * 6.关闭链接
         */
        Statement stmt = null;
        ResultSet rs = null;
        Connection conn = null;
        try {
            //1.注册数据库的驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.通过DriverManager获取数据库连接
            String url =
                    "jdbc:mysql://localhost:3306/jdbc?serverTimezone=GMT%2B8&useSSL=false";
            String username ="root";
            String password ="123456";
            conn = DriverManager.getConnection(url,username,password);
            //3.通过Conection对象获取Statement对象
            /**
             * 静态sql语句用 statement
             * 动态sql语句用preparedstatement
             */
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入你的旧账号名:" );
            String n1 = sc.next();
            System.out.println("请输入你的旧账号密码:");
            String p1 = sc.next();
            System.out.println("请输入你的新账号名:" );
            String n2 = sc.next();
            System.out.println("请输入你的新账号密码:");
            String p2 = sc.next();

            String updateSQL ="update users set name =? , password ? where name =?, password=?";
            PreparedStatement ps = conn.prepareStatement(updateSQL);
            ps.setString(1,n2);
            ps.setString(2,p2);
            ps.setString(3,n1);
            ps.setString(4,p1);
            int res= ps.executeUpdate();
//            System.out.println(res);
            if (res>0){
                System.out.println("账号密码更新成功");
            }else {
                System.out.println("账号密码更新失败");
            }
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }finally {
            //6.回收数据库资源
            if (rs != null){
                try {
                    rs.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
                rs = null;
            }if (stmt !=null){
                try {
                    stmt.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
                stmt = null;
            }if (conn !=null){
                try{
                    conn.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
                conn = null;
            }
        }
    }
}
